package com.bzchao.rocketmq.controller;

import org.apache.rocketmq.client.MQAdmin;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/mq")
public class ProducerController {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private MQAdmin mqAdmin;

    @RequestMapping("/create")
    public String createTopic() throws MQClientException {
        mqAdmin.createTopic("stringTopic", "stringTopic", 16, 16);
        return "createTopic";
    }

    @RequestMapping("/sync/send1")
    public String syncSendString() throws MQClientException {
        mqAdmin.createTopic("stringTopic", "stringTopic", 16, 16);

        //发送一个同步消息，会返回值 ---发送到 stringTopic 主题
        SendResult sendResult = rocketMQTemplate.syncSend("stringTopic", "Hello RocketMQ");
        return sendResult.toString();
    }

    /**
     * 验证RocketMQ顺序消费l
     */
    @RequestMapping("/send/ordered")
    public String sendOrderedMsg() {
        /**
         * hashKey: 为了保证报到同一个队列中，将消息发送到orderTopic主题上
         */
        rocketMQTemplate.syncSendOrderly("orderTopic", "no1", "order");
        rocketMQTemplate.syncSendOrderly("orderTopic", "no2", "order");
        rocketMQTemplate.syncSendOrderly("orderTopic", "no3", "order");
        rocketMQTemplate.syncSendOrderly("orderTopic", "no4", "order");
        rocketMQTemplate.syncSendOrderly("orderTopic", "no5", "order");
        return "success";
    }
}
